package dao;

import domain.Student;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: 朱新舜
 * @Date: 2020-04-27 11:11:05
 */
public class StudentDaoArrayList implements StudentDao {
    ArrayList<Student> list = new ArrayList<>();

    @Override
    public Student selectById(int id) {
        Iterator<Student> iterator = list.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            if (student.getId() == id) {
                return student;
            }
        }
        return null;
    }

    @Override
    public List<Student> selectAll() {
        return list;
    }

    @Override
    public void insert(Student student) {
        Student s = selectById(student.getId());
        if (s == null) {
            list.add(student);
            System.out.println("保存成功！");
        } else {
            System.out.println("保存失败！id重复了！");
        }

    }

    @Override
    public void update(int id, Student student) {
        Student s = selectById(id);
        int index = list.indexOf(s);
        list.remove(s);
        list.add(index, student);
        System.out.println("修改成功！");

    }

    @Override
    public void delete(int id) {
        Student student = selectById(id);
        if (student == null) {
            System.out.println("要删除的学生不存在！");
        } else {
            list.remove(student);
            System.out.println("删除成功！");
        }

    }
}
